#include <xp/net/inet.h>
#include <xp/bas/stdio.h>
#include <xp/bas/string.h>

int xp_main (int argc, xp_char_t* argv[])
{
	xp_uint32_t ip, ip2, nm, nm2, nw;
	xp_char_t buf[32];
	xp_size_t i;

	if (argc != 2) {
		xp_printf (XP_TEXT("%s: ip_address/netmask\n"), argv[0]);
		return -1;
	}	

	if (xp_inet4_strtoipnm (argv[1], &ip, &nm) == -1) {
		xp_printf (XP_TEXT("strtoipnm [%s] - not a valid address\n"), argv[1]);
		return -1;
	}

	if (xp_inet4_strxtoipnm (argv[1], xp_strlen(argv[1]), &ip2, &nm2) == -1) {
		xp_printf (XP_TEXT("strxtoipnm [%s] - not a valid address\n"), argv[1]);
		return -1;
	}

	if (ip != ip2 || nm != nm2) {
		xp_printf (XP_TEXT("strtoipnm and strxtoipnm have returned different values\n"));
		return -1;
	}

	nw = ip & nm;

	xp_inet4_iptostrx (ip, buf, xp_countof(buf));
	xp_printf (XP_TEXT("address [%s]\n"), buf);
	xp_inet4_iptostrx (nm, buf, xp_countof(buf));
	xp_printf (XP_TEXT("netmask [%s]\n"), buf);
	xp_inet4_iptostrx (nw, buf, xp_countof(buf));
	xp_printf (XP_TEXT("network [%s]\n"), buf);

	xp_printf (XP_TEXT("-------------------------------\n"));
	for (i = 1; i <= xp_countof(buf); i++) {
		xp_size_t len = xp_inet4_ipnmtostrx (ip, nm, buf, i);
		xp_printf (XP_TEXT("[%s] len = %d, bufsize = %d\n"), 
			buf, (int)len, (int)i);
	}

	xp_printf (XP_TEXT("-------------------------------\n"));
	for (i = 1; i <= xp_countof(buf); i++) {
		xp_size_t len = xp_inet4_ipnmtostrpx (ip, nm, buf, i);
		xp_printf (XP_TEXT("[%s] len = %d, bufsize = %d\n"), 
			buf, (int)len, (int)i);
	}

	return 0;
}
